<template>
    <div>
        <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card >
        <!-- 添加角色区域 -->
       <el-row>
           <el-col><el-button type="primary" @click="addDialogVisible = true">添加角色</el-button></el-col>
       </el-row>
       <!-- 角色列表区 -->
        <el-table :data="rolelist" border stripe>
            
            <!-- 展开角色权限列表 -->
            <el-table-column type="expand" >
                <template slot-scope="scope">
                    <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' :'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                        <!-- 渲染一级权限 -->
                        <el-col :span=5>
                            <el-tag closable @close="removeRightByid(scope.row,item1.id)">{{item1.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <!-- 渲染二级和三级权限 -->
                        <el-col :span="19" >
                            <!-- 通过for循环嵌套渲染二级权限 -->
                            <!-- i2若等于0不加上边框线 反之加上 -->
                            <el-row :class="[i2 === 0 ? '' :'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key=item2.id >
                                <!-- 二级权限 -->
                                <el-col :span="6">
                                    <el-tag type="success" closable @close="removeRightByid(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <!-- 三级权限 -->
                                <el-col :span="18">
                                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeRightByid(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
            </template>
            </el-table-column>
            <!-- 索引列 -->
           <el-table-column type="index"></el-table-column>
           <el-table-column label="角色名称" prop="roleName"></el-table-column>
           <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
           <el-table-column label="操作" prop="level">
               <template slot-scope="scope">
                   <!-- 修改信息 -->
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false" >
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)" ></el-button>
            </el-tooltip>
            <!-- 删除按钮 --> 
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false" >
              <el-button type="danger" icon="el-icon-delete"  size="mini" @click="removeRoleById(scope.row.id)" ></el-button>
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false" >
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)" ></el-button>
            </el-tooltip>
               </template>
           </el-table-column>
       </el-table>
    </el-card>
    <!-- 用户添加区域 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogVisibleClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addRoleForm"
        :rules="addRoleFoemRules"
        ref="addRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑信息区域 -->
     <el-dialog
      title="修改信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogVisibleClosed"
    >
      <el-form
        :model="editRoleForm"
        :rules="editRoleFromRules"
        ref="editRoleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 分配权限弹出框 -->
    <el-dialog
  title="分配权限"
  :visible.sync="SetRightDialogVisible"
  width="50%" @close="SetRightDialogClosed">
<!-- 树形空间 -->
  <el-tree :data="rightslist" :props="treeProps"
   show-checkbox node-key="id" default-expand-all :default-checked-keys="defkeys" ref="treeref"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="SetRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
    </div>
</template>
<script>
export default {
    data(){
        return{
            //所有角色列表信息
            rolelist:[],
            addDialogVisible:false,
            //显示分配权限
            SetRightDialogVisible:false,
            //所有权限列表
            rightslist:[],
            //树形控件绑定对象
            treeProps:{
                label:'authName',
                children:'children'
            },
            //默认选中的节点id值
            defkeys:[],
            addRoleForm:{
                roleName:'',
                roleDesc:''
            },
            roleId:'',
            addRoleFoemRules:{
                roleName:[{ required: true, message: '请输入角色名称', tigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '请输入长度在3到10个字符之间的角色名称',
            tigger: 'blur',
          }],
          roleDesc:[
              { required: false, message: '请输入角色描述', tigger: 'blur' },
          {
            min: 0,
            max: 10,
            message: '请输入长度在0到10个字符之间的角色描述',
            tigger: 'blur',
          }
          ]
            },
            editDialogVisible:false,
            editRoleForm:{},
            editRoleFromRules:{
                roleName:[{ required: true, message: '请输入角色名称', tigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '请输入长度在3到10个字符之间的角色名称',
            tigger: 'blur',
          }],
          roleDesc:[
              { required: false, message: '请输入角色描述', tigger: 'blur' },
          {
            min: 0,
            max: 10,
            message: '请输入长度在0到10个字符之间的角色描述',
            tigger: 'blur',
          }
          ],
            }
            
        }
    },
    created(){
        this.getRolelist()
    },
    methods:{
       async getRolelist(){
          const { data:res } = await this.$http.get('roles')
          if(res.meta.status !==200){
              return this.$message.error('获取角色列表失败')
          }
          this.rolelist = res.data
          console.log(this.rolelist)
        },
        //关闭对话框后清除上一次写入的内容
        addDialogVisibleClosed(){
            this.$refs.addRoleFormRef.resetFields()
        },
        //确认添加用户操作
        addRole() {
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) return
        //可以发起请求
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        //添加成功后关闭窗口
        this.addDialogVisible = false
        //重新获取刷新列表
        this.getRolelist()
      })
        },
        //根据id删除对应权限
       async removeRightByid(role,rightId){
        //弹框提示
       const confirmresult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(confirmresult !=='confirm'){
            return this.$message.info('取消删除')
        }
       const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
       if(res.meta.status !== 200){
           return this.$message.error('删除权限失败')
       }
       this.$message.success('删除权限成功')
       role.children = res.data
        },
        //删除角色
        async removeRoleById(id){
        //弹框提示是否删除数据
     const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        //若点击确认删除，返回confirm字符串
        //若点击取消删除，返回cancel字符串
        if(confirmResult !== 'confirm'){
            return this.$message.info('已取消删除')
        }
       const {data:res} = await this.$http.delete('roles/' + id)
       if(res.meta.status !==200){
           return this.$message.error('删除角色失败')
       }
       this.$message.success('成功删除角色')
       this.getRolelist()
    },
    //展示编辑用户对话框
    async showEditDialog(id) {
        // console.log(id)
        this.editDialogVisible = true
       const {data:res} = await this.$http.get('roles/' + id)
       if(res.meta.status !== 200){
           return this.$message.error('查询数据失败')
       }
        this.editRoleForm = res.data
    },
    editDialogVisibleClosed(){
        this.$refs.editRoleFormRef.resetFields()
    },
    //修改信息提交
        editRoleInfo(){
            this.$refs.editRoleFormRef.validate(async valid => {
            if(!valid) return
            //若valid为true则发起真正的数据请求
           const {data:res}=await this.$http.put('roles/' + this.editRoleForm.roleId,{roleName:this.editRoleForm.roleName,roleDesc:this.editRoleForm.roleDesc})
            if(res.meta.status !==200){
                return this.$message.error('更新角色信息失败')
            }
            this.$message.success('更新角色信息成功')
        //修改成功后关闭窗口
        this.editDialogVisible = false
        //重新获取刷新列表
        this.getRolelist()
        })
        },
       async showSetRightDialog(role){
           this.roleId = role.id
            this.getLesfkeys(role,this.defkeys)
            this.SetRightDialogVisible = true
            //获取权限数据
         const {data:res}=await this.$http.get('rights/tree')
         if(res.meta.status !==200){
             return this,$message.error('获取权限列表失败')
         }
         //把获取到的权限数据保存
         this.rightslist = res.data
         console.log(this.rightslist)
        },
        //监听对话框关闭 清空数组
        SetRightDialogClosed(){
                this.defkeys=[]
        },
        //通过递归获取三级权限并绑定到数组
        //如果当前节点不包含childre属性则是三级节点
        getLesfkeys(node,arr){
            if(!node.children){
                return arr.push(node.id)
            }

            node.children.forEach(item=>this.getLesfkeys(item,arr))
        },
        //点击分配权限
       async allotRights(){
            const keys = [
                ...this.$refs.treeref.getCheckedKeys(),
                ...this.$refs.treeref.getHalfCheckedKeys()
            ]
            const idstr = keys.join(',')
           const{data:res}=await this.$http.post(`roles/${this.roleId}/rights`,{rids:idstr})
            if(res.meta.status !==200){
                return this.$message.error('添加权限失败')
            }
            this.$message.success('添加权限成功')
            this.SetRightDialogVisible = false
            this.getRolelist()
        }
    }
}
</script>
<style lang="less" scoped>
.el-tag{
    margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
border-bottom: 1px solid #eee;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>